# -*- coding:utf-8 -*-
import os
import sys
from tempfile import TemporaryDirectory
from src.utils.runcmd import mount
from src.utils.runcmd import umount
from src.utils.runcmd import mkisofs
from src.utils.runcmd import createrepo_group
from src.utils.runcmd import cp_iso_file
from src.replace_rpms import ReplaceRPMS
from src.utils.runcmd import implant_iso_md5
from src.core.global_config import GlobalConfig
from src.utils.logger import logger


class RebuildISO(object):
    def __init__(self, iso, rpms, work_dir,
                 output, product_name, version_id, version_info, work_tmp="/var/tmp"):
        self.iso = iso
        self.rpms = rpms
        self.work_dir = work_dir
        self.output = output
        self.work_tmp = work_tmp
        self.rpm_processor = None
        self.product_name = product_name
        self.version_id = version_id
        self.version_info = version_info

    def mount_and_cp(self):
        ret = 0
        iso_mount_path = os.path.join(self.work_tmp, "iso_")
        with TemporaryDirectory(prefix=iso_mount_path, dir=self.work_tmp) as iso_dir:
            ret = mount(self.iso, iso_dir, "iso9660", "loop")
            if ret:
                logger.error("Failed to mount %s to %s", self.iso, iso_dir)
                return ret
            logger.info("ISO mounted on dir: %s", iso_dir)
            ret = cp_iso_file(iso_dir, self.work_dir)
            if ret:
                logger.error("Failed to cp iso file from %s to %s", iso_dir, self.work_dir)
                return ret
            logger.info("CP all iso files successfully!")
            ret = umount(iso_dir)
            if ret:
                logger.error("Failed to umount dior %s", iso_dir)
                return ret
        return ret

    def replace_rpms(self):
        self.rpm_processor = ReplaceRPMS(self.rpms, self.work_dir,
                                         self.product_name, self.version_id, self.version_info)
        self.rpm_processor.replace_rpms()
        pass

    def do_iso_rebuild(self):
        # mount and copy
        logger.info("We are mounting iso, and copy all files, please wait...", )
        try:
            ret = self.mount_and_cp()
            if ret:
                sys.exit(1)
        except OSError as err:
            logger.error(err)
            sys.exit(1)
        logger.info("Mount iso and copy file successfully!")
        # replace rpms
        self.replace_rpms()
        logger.info("Replace rpms for new iso successfully!")
        # recreaterepo repo for iso
        ret = createrepo_group(self.work_dir)
        if ret:
            logger.error("Failed to createrepo for dir: %s", self.work_dir)
            sys.exit(1)
        logger.info("Createrepo for new iso successfully!")
        # mkisofs for new iso
        # vid = openEuler-20.03-lts-SP1-x86_64
        # PRODUCT_NAME = openEuler
        # VERSION_INFO = 20.03-lts-SP1
        # ARCH = x86_64

        vid = GlobalConfig.PRODUCT_NAME + "-" + \
              GlobalConfig.VERSION_INFO + "-" + \
              GlobalConfig.ARCH.value
        ret = mkisofs(self.work_dir, self.output, GlobalConfig.ARCH, vid)
        if ret:
            logger.error("Failed to rebuild iso")
            sys.exit(1)
        logger.info("ISO rebuild successfully, please check: %s", self.output)
        implant_iso_md5(self.output)
